package indi.kider.server.woniubus.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import indi.kider.common.constant.RentOutlineStateCons;
import indi.kider.common.model.apabus.RentOutline;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.employee.Employee;
import indi.kider.common.model.woniubus.TenantVo;
import indi.kider.server.apabus.mapper.RentOutlineMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import indi.kider.server.woniubus.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.util.StringUtil;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@SuppressWarnings("ALL")
public class CommunityInitServiceImpl implements CommunityInitService {
    @Autowired
    private RentOutlineMapper rentOutlineMapper;
    @Autowired
    private HousesMapper housesMapper;
    @Autowired
    private WoniuBusService woniuBusService;


    /**
     * 导入房源+租客
     * @param file
     * @param communityId
     * @param fileName
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    public void importExcelHouseTenant(MultipartFile file, Long communityId,Employee employee) throws Exception{
        try {
            InputStream is = file.getInputStream();
            //    	序号	 姓名	所属单位	 性别	房号	 电表	水表
            //    	入住时间 	身份证地址	身份证号	联系电话	门禁卡有无领取	钥匙押金	押金单编号	暂住证	退宿日期
            //    	出租方式  支付方式(1,不线上支付 2，线上支付)  付费类型(1，后付费 2，预付费)  支付周期（1月，2季）	是否出房租账单1出房租账单 2不出房租账单  租金	押金	几室	几厅	网络费	物业费	电费	水费	公摊费用
            String[] names = {"xh","name","formCompy","sex","houseNumb","powerMeter","waterMeter",
                    "rentDate","cardIdAddress","cardId","phone","info1","info2","info3","info4","info5",
                    "comType","payOnline","postpaid","doPriceBill","setLease","priceSet","deposit","cnt1","cnt2","netCost","propertyCosts","powerCost","waterCost","shareCost",
            };
            List<JSONObject> list = ExcelUtil.readExcel(is, names, false);
            dealHouseAndTenantList(list,communityId,true,employee);
        }catch (Exception e){
            throw new Exception("导入过程出现异常,检查格式。异常;"+e.getMessage());
        }
    }
    public void dealHouseAndTenantList(List<JSONObject> list,Long communityId,Boolean hasDo,Employee employee)throws  Exception{
        Map<String,Long> isHouseCreateMap = new HashMap();
        for(JSONObject json : list){
            Houses house = JSON.parseObject(json.toJSONString(),Houses.class);
            Long houseId = 0L;
            if(isHouseCreateMap.get(house.getHouseNumb())!=null&&isHouseCreateMap.get(house.getHouseNumb())>0L){
                houseId = isHouseCreateMap.get(house.getHouseNumb());
            }else{
                house.setCommunityId(communityId);
                housesMapper.insertSelective(house);
                isHouseCreateMap.put(house.getHouseNumb(),house.getId());
                houseId = house.getId();

                RentOutline rentOutline = new RentOutline();
                rentOutline.setState(RentOutlineStateCons.VACANCY);
                rentOutline.setEmployeeId(employee.getId());
                rentOutline.setEnterprise(Long.valueOf(employee.getEnterpriseId()));
                rentOutline.setHousesId(houseId);
                rentOutline.setRentTime(new Date());
                rentOutline.setRemark("自动");
                rentOutlineMapper.insertSelective(rentOutline);
            }
            if(hasDo){
                TenantVo  tenantVo =  jsonToTenantVo(json,houseId,employee);
                if(StringUtil.isNotEmpty(tenantVo.getCardId())){
                    woniuBusService.rentHouse(tenantVo);
                }
            }
        }
    }
    public static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy.M.d");

    private TenantVo  jsonToTenantVo(JSONObject json,Long houseId,Employee employee)throws  Exception{
        TenantVo tenantVo = new TenantVo();
        tenantVo.setHouseId(houseId);
        tenantVo.setOpInId(employee.getId());
        String rentDate = json.getString("rentDate");
        tenantVo.setRentDate(formatter.parse(rentDate));
        String info5 = json.getString("info5");
        Date expireDate = getExpireDate(rentDate,info5);
        tenantVo.setExpireDate(expireDate);
        tenantVo.setRemark("初始化导入");
        tenantVo.setName(json.getString("name"));
        tenantVo.setPhone(json.getString("phone"));
        tenantVo.setCardId(json.getString("cardId"));
        tenantVo.setSex(json.getString("sex").equals("男")?1:2);
        tenantVo.setFormCompy(json.getString("formCompy"));
        tenantVo.setNationality(json.getString("cardIdAddress"));
        return tenantVo;
    }

    /**
     * 根据入住时间和退宿时间
     * @param rentDate
     * @return
     * @throws Exception
     */
    public static Date getExpireDate(String rentDate,String info5)throws  Exception{
        if(StringUtil.isNotEmpty(info5)) return formatter.parse(info5);
        Date date = formatter.parse(rentDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(1, 1);
        return  cal.getTime();
    }

}
